<?php
/**
 * Created by PhpStorm.
 * Script Name: Wechat.php
 * Create: 2022/12/22 14:00
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\admin\controller;

use plugin\wechat\app\AdminController;
use plugin\wechat\app\model\Setting;
use plugin\wechat\app\service\Setting as SettingService;
use plugin\wechat\app\service\OpenPlatform;
use plugin\wechat\app\service\Mp as MpService;
use support\Request;

class Wechat extends AdminController
{

    public function __construct()
    {
        parent::__construct();
        $this->model = new Setting();
    }

    /**
     * 上传开放平台校验文件
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function verifyFilePost(){
        if(request()->isPost()){
            try {
                // 获取表单上传文件 例如上传了001.jpg
                $file = request()->file('file');
                if(! $file->isValid()){
                    return $this->error("文件非法!: " . $file->getUploadErrorCode());
                }
                $file_path = '/'.$file->getUploadName();
                // 移动到服务器的上传目录 并且使用原文件名
                $file->move(public_path().$file_path);

                //保存
                $setting = SettingService::getSettings('platform');
                $setting['verify_file'] = $file_path;
                $this->model->where('name', 'platform')
                    ->update(['value' => json_encode($setting, JSON_UNESCAPED_UNICODE)]);
                return $this->success('上传成功', '', ['src' => $file_path]);
            }catch (\Exception $e){
                return $this->error('文件上传错误!:' . $e->getMessage());
            }
        }
    }

    /**
     * 获取开放平台正式版服务器域名
     * @return string
     * @throws \Exception
     * Author: fudaoji<fdj@kuryun.cn>
     */
    private function getWxaServerDomain(){
        $response = OpenPlatform::serverDomainGet();
        if(!empty($response['published_wxa_server_domain'])){
            return $response['published_wxa_server_domain'];
        }
        return '';
    }

    /**
     * 获取开放平台正式版业务域名
     * @return string
     * @throws \Exception
     * Author: fudaoji<fdj@kuryun.cn>
     */
    private function getWxaJumpDomain(){
        $response = OpenPlatform::serverDomainGet();
        if(!empty($response['wxa_jump_h5_domain'])){
            return $response['wxa_jump_h5_domain'];
        }
        return '';
    }

    /**
     * 开放平台设置
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        $setting = $this->model->where('name', 'platform')->find();
        $platform = [
            'appid' => '',
            'appsecret' => '',
            'token'  => get_rand_char(32),
            'aes_key' => get_rand_char(43),
            'verify_file' => '',
            'wxa_server_domain' => empty($setting) ? '' : $this->getWxaServerDomain(),
            'wxa_jump_h5_domain' => empty($setting) ? '' : $this->getWxaJumpDomain(),
        ];
        if(empty($setting)){
            $setting = $this->model->create([
                'name' => 'platform',
                'title' => '微信开放平台',
                'value' => json_encode($platform, JSON_UNESCAPED_UNICODE)
            ]);
        }else{
            $platform_setting = json_decode($setting['value'], true);
            $platform = array_merge($platform, $platform_setting);
        }

        if(request()->isPost()){
            $post_data = input('post.');
            $data = array_merge($platform, $post_data);
            if($res = $this->model->update([
                'id' => $setting['id'],
                'value' => json_encode($data, JSON_UNESCAPED_UNICODE)
            ])){
                if(!empty($post_data['wxa_server_domain'])){
                    if(is_string($res = OpenPlatform::serverDomainModify($post_data))){
                        return $this->error($res);
                    }
                }
                if(!empty($post_data['wxa_jump_h5_domain'])){
                    if(is_string($res = OpenPlatform::jumpDomainModify($post_data))){
                        return $this->error($res);
                    }
                }
                SettingService::getSettings('platform', true); // refresh setting
                return $this->success('操作成功!');
            }
            return $this->error('操作失败!');
        }

        $assign = [
            'platform' => $platform
        ];
        return $this->show($assign);
    }

    /**
     * 平台账号设定
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function config(){
        $current_name = input('name', 'default_app');
        $config = $this->model->where('name', $current_name)->find();

        $data = empty($config['value']) ? [] : json_decode($config['value'], true);

        $builder = new FormBuilder();
        switch ($current_name){
            case 'default_app':
                $builder->setTip("填写的appid必须是在本<a class='layui-font-red' target='_blank' href='".\request()->domain()."/app/wechat/tenant'>平台商户端</a>授权接入过的公众号或小程序才可以")
                    ->addFormItem('mp_appid', 'text', '平台公众号', '请填写已接入平台的公众号appid，将作为通用公众号', [], 'required');
                break;
        }
        $builder->setPostUrl(url('savePost', ['name' => $current_name]))
            ->setFormData($data);
        return $builder->show();
    }

    public function savePost(Request $request, $jump = '', $data = []){
        $post_data = input('post.');
        unset($post_data['__token__']);
        $current_name = input('name', '');
        switch ($current_name){
            case 'default_app':
                $mp = MpService::getInfo($post_data['mp_appid']);
                if(empty($mp) || !$mp['is_auth']){
                    return $this->error('此公众号未在平台授权！');
                }
                break;
        }
        $config = $this->model->where('name', $current_name)->find();
        $value = json_encode($post_data);
        if(empty($config)){
            $this->model->createOne([
                'name' => $current_name,
                'title' => '平台账号',
                'value' => $value,
            ]);
        }else{
            $this->model->update([
                'id' => $config['id'],
                'value' => $value
            ]);
        }

        return $this->success('操作成功！', url('config', ['name' => $current_name]));
    }
}